install.packages("plotly")
install.packages("gapminder")
install.pacakges("tidyverser")
library(plotly)
library(gapminder)
library(tidyverse)還記得 Hans Rosling 的 The best stats you’ve ever seen 嗎?
dim(gapminder)## [1] 1704 6
head(gapminder)## # A tibble: 6 x 6
## country continent year lifeExp pop gdpPercap
## <fctr> <fctr> <int> <dbl> <int> <dbl>
## 1 Afghanistan Asia 1952 28.801 8425333 779.4453
## 2 Afghanistan Asia 1957 30.332 9240934 820.8530
## 3 Afghanistan Asia 1962 31.997 10267083 853.1007
## 4 Afghanistan Asia 1967 34.020 11537966 836.1971
## 5 Afghanistan Asia 1972 36.088 13079460 739.9811
## 6 Afghanistan Asia 1977 38.438 14880372 786.1134
gapminder_2007 <- gapminder %>%
filter(year == 2007)
p <- plot_ly(data = gapminder_2007, x = ~gdpPercap, type = "histogram")pp <- plot_ly(data = gapminder_2007, x = ~continent, y = ~lifeExp, color = ~continent, type = "box")pp <- plot_ly(data = gapminder_2007, x = ~gdpPercap, y = ~lifeExp, color = ~continent, type = "scatter", mode = "markers")pnorth_asia <- gapminder_2007 %>%
filter(country %in% c("China", "Taiwan", "Japan", "Korea, Rep."))
north_asia$country <- as.character(north_asia$country)
p <- plot_ly(data = north_asia, x = ~country, y = ~gdpPercap, type = "bar", color = ~country)ptwn <- gapminder %>%
filter(country == "Taiwan")
p <- plot_ly(data = twn, x = ~year, y = ~lifeExp, type = "scatter", mode = "lines")pnorth_asia <- gapminder %>%
filter(country %in% c("China", "Taiwan", "Japan", "Korea, Rep."))
north_asia$country <- as.character(north_asia$country)
p1 <- north_asia %>%
filter(country == "Japan") %>%
plot_ly(x = ~year, y = ~gdpPercap, type = "scatter", mode = "lines") %>%
add_lines(name = ~"Japan")
p2 <- north_asia %>%
filter(country == "Korea, Rep.") %>%
plot_ly(x = ~year, y = ~gdpPercap, type = "scatter", mode = "lines") %>%
add_lines(name = ~"Korea, Rep.")subplot 函數subplot(p1, p2)gapminder_1952 <- gapminder %>%
filter(year == 1952)
bubble_1952 <- gapminder_1952 %>%
plot_ly(x = ~gdpPercap, y = ~lifeExp, color = ~continent, size = ~pop, type = "scatter", mode = "markers", sizes = c(10, 1000), text = ~country)bubble_1952bubble_1952_log <- gapminder_1952 %>%
plot_ly(x = ~gdpPercap, y = ~lifeExp, color = ~continent, size = ~pop, type = "scatter", mode = "markers", sizes = c(10, 1000), text = ~country) %>%
layout(xaxis = list(type = "log"))bubble_1952_log新增 frame = ~year 參數
bubble_chart <- gapminder %>%
plot_ly(x = ~gdpPercap, y = ~lifeExp, color = ~continent, size = ~pop, type = "scatter", mode = "markers", sizes = c(10, 1000), text = ~country, frame = ~year) %>%
layout(title = "Gapminder Data Visualization",
xaxis = list(title = "GDP Per Capita", type = "log"),
yaxis = list(title = "Life Expectancy"))bubble_chart